package cn.com.efuture.o2o.backend.api.product;

import cn.com.efuture.o2o.backend.mybatis.entity.Dept;
import cn.com.efuture.o2o.backend.mybatis.entity.O2oCategory;
import cn.com.efuture.o2o.backend.mybatis.entity.O2oGoodsFilter;
import cn.com.efuture.o2o.backend.mybatis.entity.O2oProduct;
import cn.com.efuture.o2o.backend.mybatis.service.O2oCategoryServiceImpl;
import cn.com.efuture.o2o.backend.mybatis.service.ProductServiceImpl;
import cn.com.efuture.o2o.backend.system.JsonResponse;
import cn.com.efuture.o2o.backend.util.ParameterHelper;
import cn.com.efuture.o2o.backend.util.SessionHelper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/product")
public class ProductController {
    private final ProductServiceImpl productServiceImpl;
    private final O2oCategoryServiceImpl o2oCategoryServiceImpl;
    protected org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${FILE_URL}")
    private String URL;

    public ProductController(ProductServiceImpl productServiceImpl, O2oCategoryServiceImpl o2oCategoryServiceImpl) {
        this.productServiceImpl = productServiceImpl;
        this.o2oCategoryServiceImpl = o2oCategoryServiceImpl;
    }

    @ApiOperation(value = "获取主档商品列表", notes = "获取主档商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "itemCode", value = "商品编码", dataType = "String"),
            @ApiImplicitParam(name = "goodsName", value = "商品名称", dataType = "String"),
            @ApiImplicitParam(name = "barcode", value = "商品条码", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "page", required = true, dataType = "Int"),
            @ApiImplicitParam(name = "pageSize", value = "pageSize", required = true, dataType = "Int")
    })
    @RequestMapping(value = "/getProductList", method = RequestMethod.GET)
    public JsonResponse getProductList(@RequestParam(name = "data") String data) {
        logger.info("------------getProductList-----------");
        Map<String, Object> map = JSONObject.parseObject(data);
        try {
            ParameterHelper.cookPageInfo(map);
            //设置分页信息
            PageHelper.startPage((int) map.get("page"), (int) map.get("pageSize"));
            //执行查询
            List<O2oProduct> list = productServiceImpl.getProductList(map);
            //获取查询结果
            PageInfo<O2oProduct> pageInfo = new PageInfo<>(list);
            return JsonResponse.ok(pageInfo.getTotal(), list);
        } catch (Exception e) {
            logger.error(e.toString());
            return JsonResponse.SERVER_ERR;
        }
    }

    @ApiOperation(value = "获取主档商品信息", notes = "获取主档商品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "itemId", value = "内部货品编码", required = true, dataType = "Int")
    })
    @RequestMapping(value = "/getProduct", method = RequestMethod.GET)
    public JsonResponse getProduct(@RequestParam(name = "data") String data) {
        logger.info("------------getProduct-----------");
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> map = JSONObject.parseObject(data);
        try {
            StringBuilder categoryNames = new StringBuilder();
            StringBuilder p4CategoryNames = new StringBuilder();
            O2oProduct o2oProduct = productServiceImpl.getProduct(map);
            jsonObject.put("categoryId", o2oProduct.getCategoryId());
            //获取o2o类别
            O2oCategory o2oCategory = o2oCategoryServiceImpl.getCategory(jsonObject);
            o2oProduct.setParentCategoryId(o2oCategory.getParentCategoryId());
            o2oProduct.setCategoryName(o2oCategory.getCategoryName());
            categoryNames.append(o2oCategory.getCategoryName());
            while (!"0".equals(o2oCategory.getParentCategoryId())) {
                categoryNames.insert(0, "->");
                jsonObject.put("categoryId", o2oCategory.getParentCategoryId());
                o2oCategory = o2oCategoryServiceImpl.getCategory(jsonObject);
                categoryNames.insert(0, o2oCategory.getCategoryName());
            }
            o2oProduct.setCategoryNames(categoryNames.toString());
            //获取业务系统类别
            jsonObject.put("deptId", o2oProduct.getErpCategoryId());
            Dept dept = o2oCategoryServiceImpl.getDept(jsonObject);
            p4CategoryNames.append(dept.getName());
            while (!"0".equals(dept.getParentId())) {
                p4CategoryNames.insert(0, "->");
                jsonObject.put("deptId", dept.getParentId());
                dept = o2oCategoryServiceImpl.getDept(jsonObject);
                p4CategoryNames.insert(0, dept.getName());
            }
            o2oProduct.setP4CategoryNames(p4CategoryNames.toString());
            String url = URL + "/image/read/";
            o2oProduct.setImageUrl1(url + o2oProduct.getImageKey1());
            o2oProduct.setImageUrl2(url + o2oProduct.getImageKey2());
            return JsonResponse.ok(o2oProduct);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JsonResponse.notOk(JsonResponse.ERR, e.getMessage());
        }
    }

    @ApiOperation(value = "批量修改主档商品信息", notes = "批量修改主档商品信息")
    @RequestMapping(value = "/updateProducts", method = RequestMethod.POST)
    public JsonResponse updateProducts(@RequestParam(value = "data") String data, HttpServletRequest request) {
        logger.info("------------updateChannelShops-----------");
        List<O2oProduct> O2oProducts = JSONObject.parseArray(data, O2oProduct.class);
        String userName = request.getSession().getAttribute("username").toString();
        try {
            for (O2oProduct o2oProduct : O2oProducts) {
                Integer oldStatus = o2oProduct.getOldStatus();
                Integer newStatus = o2oProduct.getNewStatus();
                if ("0".equals(o2oProduct.getCategoryId())) {
                    return JsonResponse.notOk("[" + o2oProduct.getItemCode() + "]" + o2oProduct.getGoodsName() + "请选择类别");
                }
                if (oldStatus != 0 && newStatus == 0) {
                    return JsonResponse.notOk("[" + o2oProduct.getItemCode() + "]" + o2oProduct.getGoodsName() + "已启用商品不能修改成未启用");
                }
                if (oldStatus == 0 && newStatus == -1) {
                    return JsonResponse.notOk("[" + o2oProduct.getItemCode() + "]" + o2oProduct.getGoodsName() + "未启用商品不能修改成禁用");
                }
                if (oldStatus == -1 && newStatus == -1) {
                    return JsonResponse.notOk("禁用商品只能修改状态列");
                }
                productServiceImpl.updateProduct(o2oProduct, userName);
            }
            return JsonResponse.ok("成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JsonResponse.notOk(JsonResponse.ERR, e.getMessage());
        }
    }

    @ApiOperation(value = "获取商品主档筛选列表", notes = "获取商品主档筛选列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shopId", value = "门店编码", dataType = "String"),
            @ApiImplicitParam(name = "itemCode", value = "商品编码", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "Int"),
            @ApiImplicitParam(name = "page", value = "page", required = true, dataType = "Int"),
            @ApiImplicitParam(name = "pageSize", value = "pageSize", required = true, dataType = "Int")
    })
    @RequestMapping(value = "/getO2oGoodsFilterList", method = RequestMethod.GET)
    public JsonResponse getO2oGoodsFilterList(@RequestParam(name = "data") String data) {
        logger.info("------------getO2oGoodsFilterList-----------");
        JSONObject map = JSONObject.parseObject(data);
        try {
        	ParameterHelper.cookCityInfo(map);
            ParameterHelper.cookPageInfo(map);
            //设置分页信息
            PageHelper.startPage((int) map.get("page"), (int) map.get("pageSize"));
            //执行查询
            List<Map<String, Object>> list = productServiceImpl.getO2oGoodsFilterList(map);
            //获取查询结果
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
            return JsonResponse.ok(pageInfo.getTotal(), list);
        } catch (Exception e) {
            logger.error(e.toString());
            return JsonResponse.SERVER_ERR;
        }
    }

    @ApiOperation(value = "新增主档商品筛选信息", notes = "新增主档商品筛选信息")
    @RequestMapping(value = "/insertO2oGoodsFilter", method = RequestMethod.POST)
    public JsonResponse insertO2oGoodsFilter(@RequestParam(value = "data") String data) {
        logger.info("------------insertO2oGoodsFilter-----------");
        O2oGoodsFilter o2oGoodsFilter = JSONObject.parseObject(data, O2oGoodsFilter.class);
        String userName = SessionHelper.getUserName();
        try {
            //执行更新
            productServiceImpl.insertO2oGoodsFilter(o2oGoodsFilter, userName);
            return JsonResponse.ok("新增成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JsonResponse.notOk(JsonResponse.ERR, e.getMessage());
        }
    }
/*

    @ApiOperation(value = "修改主档商品信息", notes = "修改主档商品信息")
    @RequestMapping(value = "/updateProduct", method = RequestMethod.POST)
    public JsonResponse updateProduct(@RequestBody O2oProduct o2oProduct) {
        logger.info("------------updateChannelShop-----------");
        String userName = SessionHelper.getUserName();
        try {
            //执行更新
            productServiceImpl.updateProduct(o2oProduct,userName);
            return JsonResponse.ok("修改成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JsonResponse.notOk(JsonResponse.ERR, e.getMessage());
        }
    }
*/

    @ApiOperation(value = "导出主档商品列表模板", notes = "导出主档商品列表模板")
    @RequestMapping(value = "/exportProductList", method = RequestMethod.GET)
    public ModelAndView exportProductList(ModelMap model, @RequestParam(value = "data",required = false) String data) {
        Map<String, Object> map = JSONObject.parseObject(data);
        logger.info("------------exportProductList-----------");
        AbstractXlsView abstractxlsView = productServiceImpl.exportProductList(map);
        return new ModelAndView(abstractxlsView, model);
    }

}
